package com.vay.de.dang.online.ui.sign;

import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.URLSpan;

import com.vay.de.dang.online.R;
import com.vay.de.dang.online.databinding.ActivityLoginBinding;
import com.vay.de.dang.online.entiy.BuriedPointEntity;
import com.vay.de.dang.online.entiy.PropertyRuleEntity;
import com.vay.de.dang.online.entiy.RuleNotEmptyEntity;
import com.vay.de.dang.online.entiy.RuleRegexpEntity;
import com.vay.de.dang.online.entiy.RuleStringLengthEntity;
import com.vay.de.dang.online.ui.BaseActivity;
import com.vay.de.dang.online.ui.HomeActivity;
import com.vay.de.dang.online.util.ClickURLSpan;
import com.vay.de.dang.online.util.LocationHelper;
import com.vay.de.dang.online.util.PermissionUtil;
import com.vay.de.dang.online.util.VnDefine;
import com.vay.de.dang.online.util.VnTextWatcher;
import com.vay.de.dang.online.util.VnUtil;
import com.vay.de.dang.online.web.BaseApi;
import com.vay.de.dang.online.web.LoginApi;
import com.vay.de.dang.online.web.ReqCallback;
import com.vay.de.dang.online.web.ReqResult;

import cc.taylorzhang.singleclick.SingleClickUtil;

public class SignInActivity extends BaseActivity {

    private ActivityLoginBinding binding;
    private String applyNo;
    private PropertyRuleEntity ruleEntity;
    private boolean requestLocation;
    private long enterTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        String html = getString(R.string.login_agree)
                + "<a href=\"" + VnDefine.PrivacyPolicyUrl + "\"><font color=\"#FF2929\">" + getString(R.string.label_privacy_agreement) + "</font></a>";
        binding.privacy.setText(Html.fromHtml(html));
        binding.privacy.setMovementMethod(LinkMovementMethod.getInstance());
        Spannable cbText = (Spannable) binding.privacy.getText();
        int end = cbText.length();
        URLSpan[] urls = cbText.getSpans(0, end, URLSpan.class);
        SpannableStringBuilder style = new SpannableStringBuilder(cbText);
        style.clearSpans();
        for (URLSpan url : urls) {
            ClickURLSpan urlSpan = new ClickURLSpan(mActivity, url.getURL());
            style.setSpan(urlSpan, cbText.getSpanStart(url),
                    cbText.getSpanEnd(url), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        binding.privacy.setText(style);

        if (getIntent() != null) {
            applyNo = getIntent().getStringExtra("applyNo");
        }

        enterTime = System.currentTimeMillis();

        // send code
        SingleClickUtil.onSingleClick(binding.bntSend, view -> {
            if (!PermissionUtil.checkPermission(mActivity, PermissionUtil.getLoginPermission())) {
                PermissionUtil.requestPermission(mActivity, PermissionUtil.getLoginPermission(),
                        (allGranted, grantedList, deniedList) -> {
                            callSendOrLogin(1);
                        });
            } else {
                callSendOrLogin(1);
            }
        });

        // login
        SingleClickUtil.onSingleClick(binding.bntLogin, v -> {
            callLogin();
        });

        // 监听验证码
        binding.edCode.addTextChangedListener(new VnTextWatcher() {

            @Override
            public void afterTextChanged(Editable editable) {
                String ss = editable.toString().trim();
                if (ss.length() == 4) {
                    callLogin();
                }
            }
        });

        LoginApi.mobileRule(new ReqCallback(mActivity) {
            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {
                    ruleEntity = (PropertyRuleEntity) value.result;
                }
            }
        }.showDialog(true));
    }

    private void callLogin() {
        if (!PermissionUtil.checkPermission(mActivity, PermissionUtil.getLoginPermission())) {
            PermissionUtil.requestPermission(mActivity, PermissionUtil.getLoginPermission(),
                    (allGranted, grantedList, deniedList) -> {
                        callSendOrLogin(2);
                    });
        } else {
            callSendOrLogin(2);
        }
    }

    private void callSendOrLogin(int flag) {

        // 启动定位
        if (!requestLocation) {
            LocationHelper.getInstance().requestLocation();
            requestLocation = true;
        }

        String phone = binding.edPhone.getText().toString();
        String code = binding.edCode.getText().toString();

        if (ruleEntity != null) {
            RuleNotEmptyEntity notEmpty = ruleEntity.getNotEmpty();
            if (notEmpty != null) {
                if (VnUtil.isEmpty(phone)) {
                    showHint(notEmpty.getMessage());
                    return;
                }
            }
        } else {
            if (TextUtils.isEmpty(phone)) {
                showHint(R.string.error_phone);
                return;
            }
        }

        if (ruleEntity != null) {
            RuleStringLengthEntity stringLength = ruleEntity.getStringLength();
            if (stringLength != null) {
                /*int size = phone.length();
                if (size < stringLength.getMin() || size > stringLength.getMax()) {
                    showHint(stringLength.getMessage());
                    return;
                }*/
            }

            RuleRegexpEntity regexp = ruleEntity.getRegexp();
            if (regexp != null) {
                /*if (!phone.matches(regexp.getRegexp())) {
                    showHint(regexp.getMessage());
                    return;
                }*/
            }
        }

        // send code
        if (flag == 1) {

            // 业务埋点
            BaseApi.execBuriedPoint(1530, 1500, "登录", "获取验证码",
                    phone, (int) (System.currentTimeMillis() - enterTime));

            LoginApi.sendCode(phone, new ReqCallback(mActivity) {
                @Override
                public void callback(ReqResult value) {
                    if (value.isOk()) {
                        binding.bntSend.startCountDown();
                    }
                }
            }.showDialog(true));
        } else {

            if (TextUtils.isEmpty(code)) {
                showHint(R.string.error_v_code);
                return;
            }

            // 登录埋点
            BuriedPointEntity req1 = BaseApi.reqBuriedPoint(1510, 1500,
                    "登录", "登录(页面可见)");
            req1.setBuryingPointRemark(VnUtil.isEmpty(applyNo) ? "" : applyNo);
            BaseApi.execBuriedPoint(req1);

            // 手机号码
            BuriedPointEntity req2 = BaseApi.reqBuriedPoint(1520, 1500,
                    "登录", "手机号");
            req2.setBuryingPointRemark(phone);
            req2.setEventTime((int) (System.currentTimeMillis() - enterTime));
            BaseApi.execBuriedPoint(req2);

            // 登录
            LoginApi.login(phone, code, new ReqCallback(mActivity) {
                @Override
                public void callback(ReqResult value) {
                    HomeActivity.reOpen(mActivity);
                    finish();
                }
            }.showDialog(true));
        }
    }
}
